<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>

      <a-button @click="changheTableStyle" >{{changeTableStyleText}}</a-button>

      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
            <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
            
            <viewer :images="getImgs(text)" v-else>
                <img v-for="(item,index) in getImgs(text)" :key="index"
                 :src="item" height="25px" style="max-width:80px;font-size: 12px;font-style: italic;margin:0 1px">
            </viewer>
            <!--
            <a-modal v-if="previewImages.length > 0" :visible="previewVisible" :footer="null" @cancel="handlePreviewImageCancel">
                <img alt="example" style="width: 100%" :src="previewImages[previewImageIndex]" />
            </a-modal>
            -->
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="checkSingleBtnOnclick(record, 1)">通过</a>

          <a-divider type="vertical" />
          <a @click="checkSingleBtnOnclick(record, 0)" style="color:red">驳回</a>

          <a-divider type="vertical" />

          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a>删除</a>
          </a-popconfirm>
          
        </span>

      </a-table>
    </div>

  </a-card>
</template>

<script>
    import { filterObj } from '@/utils/util';
    import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
    import '@/assets/less/TableExpand.less'

  export default {
    name: 'singleApartCheck',
    components: {
      
    },
    data () {
      return {
        description: '职工表管理页面',
        // 表头
        columns: [],
        tableStyle : 1,

        queryParam: {},
        dataSource:[],
        ipagination:{
            current: 1,
            pageSize: 10,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
        },
        isorter:{
            column: 'createTime',
            order: 'desc',
        },
        filters: {},
        loading:false,
        selectedRowKeys: [],
        selectionRows: [],
        superQueryFlag:false,
        superQueryParams: '',
        superQueryMatchType: 'and',


        detailColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'姓名',
            align:"center",
            dataIndex: 'name'
          },
          {
            title:'性别',
            align:"center",
            dataIndex: 'sex_dictText'
          },
          {
            title:'集团',
            align:"center",
            dataIndex: 'gro'
          },
          {
            title:'站段',
            align:"center",
            dataIndex: 'station'
          },
          {
            title:'车间',
            align:"center",
            dataIndex: 'shop'
          },
          {
            title:'电话',
            align:"center",
            dataIndex: 'tel'
          },
          {
            title:'年龄',
            align:"center",
            dataIndex: 'age'
          },
          {
            title:'工龄',
            align:"center",
            dataIndex: 'seniority'
          },
          {
            title:'身份证号',
            align:"center",
            dataIndex: 'idcard'
          },
          {
            title:'身份证人像图',
            align:"center",
            dataIndex: 'idcardFront',
            scopedSlots: {customRender: 'imgSlot'}
          },
          {
            title:'身份证国徽图',
            align:"center",
            dataIndex: 'idcardBack',
            scopedSlots: {customRender: 'imgSlot'}
          },
          {
            title:'户口所在地',
            align:"center",
            dataIndex: 'household'
          },
          {
            title:'家庭地址',
            align:"center",
            dataIndex: 'address'
          },
          {
            title:'是否结婚',
            align:"center",
            dataIndex: 'ismarried_dictText'
          },
          {
            title:'配偶姓名',
            align:"center",
            dataIndex: 'sname'
          },
          {
            title:'配偶身份证',
            align:"center",
            dataIndex: 'sidcard'
          },
          {
            title:'配偶工作单位',
            align:"center",
            dataIndex: 'sworkCompany'
          },
          {
            title:'配偶工作地',
            align:"center",
            dataIndex: 'swordPlace'
          },
          {
            title:'配偶户口所在地',
            align:"center",
            dataIndex: 'shousehold'
          },
          {
            title:'岗位',
            align:"center",
            dataIndex: 'jobName'
          },
          {
            title:'职称',
            align:"center",
            dataIndex: 'jobTitle'
          },
          {
            title:'职位级别',
            align:"center",
            dataIndex: 'jobLevel'
          },
          {
            title:'项目号',
            align:"center",
            dataIndex: 'projectId'
          },
          {
            title:'项目名',
            align:"center",
            dataIndex: 'projectName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:160,
            scopedSlots: { customRender: 'action' }
          },
        ],
        simpleColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'姓名',
            align:"center",
            dataIndex: 'name'
          },
          {
            title:'电话',
            align:"center",
            dataIndex: 'tel'
          }, 
          {
            title:'项目号',
            align:"center",
            dataIndex: 'projectId'
          },
          {
            title:'项目名',
            align:"center",
            dataIndex: 'projectName'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:160,
            scopedSlots: { customRender: 'action' }
          },
        ],

        // previewVisible: true,
        // previewImages: [
        //     'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=85690711,3884201894&fm=27&gp=0.jpg',
        //     'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3564877025,796183547&fm=27&gp=0.jpg'
        // ],
        // previewImageIndex: 0,

        url: {
          list: "/single/znzfNeedSingle/listByOrgCode",
          delete: "",
          deleteBatch: "",
          checkSingleApartApply: "/single/znzfNeedSingle/passOrDeny",
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
        this.loadData();
        this.getSuperFieldList();
        this.columns = this.detailColumns;
        this.tableStyle = 1;
    },
    computed: {
        changeTableStyleText(){
            if(this.tableStyle === 1){
                return '精简表格'
            }
            else{
                return '详细表格'
            }
        }
    },
    methods: {
        getSuperFieldList(){
            let fieldList=[];
            fieldList.push({type:'string',value:'no',text:'职工号',dictCode:''})
            fieldList.push({type:'string',value:'name',text:'姓名',dictCode:''})
            fieldList.push({type:'string',value:'tel',text:'电话',dictCode:''})
            fieldList.push({type:'int',value:'age',text:'年龄',dictCode:''})
            fieldList.push({type:'double',value:'seniority',text:'工龄',dictCode:''})
            fieldList.push({type:'string',value:'idcard',text:'身份证号',dictCode:''})
            fieldList.push({type:'int',value:'sex',text:'性别',dictCode:'sex'})
            fieldList.push({type:'string',value:'gro',text:'集团',dictCode:''})
            fieldList.push({type:'string',value:'station',text:'站段',dictCode:''})
            fieldList.push({type:'string',value:'shop',text:'车间',dictCode:''})
            fieldList.push({type:'string',value:'household',text:'户口所在地',dictCode:''})
            fieldList.push({type:'string',value:'address',text:'家庭地址',dictCode:''})
            fieldList.push({type:'int',value:'ismarried',text:'是否结婚',dictCode:'yn'})
            fieldList.push({type:'string',value:'sname',text:'配偶姓名',dictCode:''})
            fieldList.push({type:'string',value:'sidcard',text:'配偶身份证',dictCode:''})
            fieldList.push({type:'string',value:'sworkCompany',text:'配偶工作单位',dictCode:''})
            fieldList.push({type:'string',value:'swordPlace',text:'配偶工作地',dictCode:''})
            fieldList.push({type:'string',value:'shousehold',text:'配偶户口所在地',dictCode:''})
            fieldList.push({type:'string',value:'jobName',text:'岗位',dictCode:''})
            fieldList.push({type:'string',value:'jobTitle',text:'职称',dictCode:''})
            fieldList.push({type:'string',value:'jobLevel',text:'职位级别',dictCode:''})
            fieldList.push({type:'string',value:'projectId',text:'房源号'})
            fieldList.push({type:'string',value:'projectName',text:'产权证号'})
            this.superFieldList = fieldList
        },
        changheTableStyle(){
            if(this.tableStyle === 1 ){
                this.tableStyle = 0
                this.columns = this.simpleColumns
            }
            else if(this.tableStyle === 0){
                this.tableStyle = 1
                this.columns = this.detailColumns
            }
            else{
                this.tableStyle = 1
                this.columns = this.detailColumns
            }
        },

        loadData(arg) {
            if(!this.url.list){
                this.$message.error("请设置url.list属性!")
                return
            }
            //加载数据 若传入参数1则加载第一页的内容
            if (arg === 1) {
                this.ipagination.current = 1;
            }
            var params = this.getQueryParams();//查询条件
            this.loading = true;
            getAction(this.url.list, params).then((res) => {
                if (res.success) {
                this.dataSource = res.result.records||res.result;
                if(res.result.total)
                {
                    this.ipagination.total = res.result.total;
                }else{
                    this.ipagination.total = 0;
                }
                }else{
                this.$message.warning(res.message)
                }
            }).finally(() => {
                this.loading = false
            })
        },
        handleSuperQuery(params, matchType) {
            //高级查询方法
            if(!params){
                this.superQueryParams=''
                this.superQueryFlag = false
            }else{
                this.superQueryFlag = true
                this.superQueryParams=JSON.stringify(params)
                this.superQueryMatchType = matchType
            }
            this.loadData(1)
        },
        getQueryParams() {
            //获取查询条件
            let sqp = {}
            if(this.superQueryParams){
                sqp['superQueryParams']=encodeURI(this.superQueryParams)
                sqp['superQueryMatchType'] = this.superQueryMatchType
            }
            var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
            param.field = this.getQueryField();
            param.pageNo = this.ipagination.current;
            param.pageSize = this.ipagination.pageSize;
            return filterObj(param);
        },
        getQueryField() {
            //TODO 字段权限控制
            var str = "id,";
            this.columns.forEach(function (value) {
                str += "," + value.dataIndex;
            });
            return str;
        },

        onSelectChange(selectedRowKeys, selectionRows) {
            this.selectedRowKeys = selectedRowKeys;
            this.selectionRows = selectionRows;
        },
        onClearSelected() {
            this.selectedRowKeys = [];
            this.selectionRows = [];
        },
        searchQuery() {
            this.loadData(1);
            // 点击查询清空列表选中行
            // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
            this.selectedRowKeys = []
            this.selectionRows = []
        },
        superQuery() {
            this.$refs.superQueryModal.show();
        },
        searchReset() {
            this.queryParam = {}
            this.loadData(1);
        },
        batchDel: function () {
            if(!this.url.deleteBatch){
                this.$message.error("请设置url.deleteBatch属性!")
                return
            }
            if (this.selectedRowKeys.length <= 0) {
                this.$message.warning('请选择一条记录！');
                return;
            } else {
                var ids = "";
                for (var a = 0; a < this.selectedRowKeys.length; a++) {
                    ids += this.selectedRowKeys[a] + ",";
                }
                var that = this;
                this.$confirm({
                title: "确认删除",
                content: "是否删除选中数据?",
                onOk: function () {
                    that.loading = true;
                    deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
                    if (res.success) {
                        //重新计算分页问题
                        that.reCalculatePage(that.selectedRowKeys.length)
                        that.$message.success(res.message);
                        that.loadData();
                        that.onClearSelected();
                    } else {
                        that.$message.warning(res.message);
                    }
                    }).finally(() => {
                    that.loading = false;
                    });
                }
                });
            }
        },
        handleDelete: function (id) {
            if(!this.url.delete){
                this.$message.error("请设置url.delete属性!")
                return
            }
            var that = this;
            deleteAction(that.url.delete, {id: id}).then((res) => {
                if (res.success) {
                //重新计算分页问题
                that.reCalculatePage(1)
                that.$message.success(res.message);
                that.loadData();
                } else {
                that.$message.warning(res.message);
                }
            });
        },
        reCalculatePage(count){
            //总数量-count
            let total=this.ipagination.total-count;
            //获取删除后的分页数
            let currentIndex=Math.ceil(total/this.ipagination.pageSize);
            //删除后的分页数<所在当前页
            if(currentIndex<this.ipagination.current){
                this.ipagination.current=currentIndex;
            }
            console.log('currentIndex',currentIndex)
        },
        handleTableChange(pagination, filters, sorter) {
            //分页、排序、筛选变化时触发
            //TODO 筛选
            console.log(pagination)
            if (Object.keys(sorter).length > 0) {
                this.isorter.column = sorter.field;
                this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
            }
            this.ipagination = pagination;
            this.loadData();
        },
        // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
        getPopupField(fields){
            return fields.split(',')
        },
        /* 图片预览 */
        getImgs(text){
            if(!text){
                return [];
            }
            let list = [];
            for(let p of this.getPopupField(text)){
                list.push(getFileAccessHttpUrl(p));
            }
            return list;
        },
        getFirstImg(text){
            if(text && text.indexOf(",")>0){
                text = text.substring(0,text.indexOf(","))
            }
            return getFileAccessHttpUrl(text)
        },
        downloadFile(text){
            if(!text){
                this.$message.warning("未知的文件")
                return;
            }
            if(text.indexOf(",")>0){
                text = text.substring(0,text.indexOf(","))
            }
            let url = getFileAccessHttpUrl(text)
            window.open(url);
        },


        checkSingleBtnOnclick(record, ret){
            if(!record.id){
                this.$message.warning('未选择项！')
                return;
            }
            if(!this.url.checkSingleApartApply){
                this.$message.error("请设置url.checkSingleApartApply属性!")
                return
            }
            var that = this;
            this.$confirm({
                title: '再次确认，若驳回请在下方输入原因?',
                content: h => <a-textarea placeholder="请输入审核意见" rows="4" id="checkSingleApplyTextarea" />,
                onOk() {
                    let note = document.getElementById('checkSingleApplyTextarea').value;
                    
                    let params = {
                        ret: ret,
                        note: note,
                        id: record.id,
                    }
                    
                    postAction(that.url.checkSingleApartApply, params).then((res) => {
                        if (res.success) {
                            that.$message.success('审核成功');
                            that.loadData();
                        } else {
                            that.$message.warning(res.message);
                        }
                    });
                    
                },
                onCancel() {
                    
                },
                class: 'test',
            });
        },


        // handlePreviewImageCancel(){
        //     this.previewVisible = false;
        // },
        // pictureOnclick(path){
        //     console.log(path);

        //     if(!path || path === ''){
        //         this.$message.warning('图片显示出错，请刷新再试！');
        //         return;
        //     }
            
        //     if(this.getPopupField(path).length <= 0){
        //         this.$message.warning('图片显示出错，请刷新再试！');
        //         return;
        //     }
        //     this.previewImages = this.getPopupField(path);
        //     this.previewImageIndex = 0;
        //     this.previewVisible = true;

        // }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>